<template>
  <!-- 新增订单分析 -->
  <div>
    <TopFilter
      :list="topFilterList"
      :cols="4"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>
    <div>
      <div class="maintop">
        <el-tabs class="lazyLoadTab" v-model="activeName" @tab-click="handleClick">
          <el-tab-pane class="lazyLoadTabPane" label="团队" name="first"></el-tab-pane>
          <el-tab-pane class="lazyLoadTabPane" label="产品" name="second"></el-tab-pane>
        </el-tabs>
      </div>

      <div class="tabShow">
        <!-- <potenCusModal v-if="activeName === 'first'" :dataSource="dataSource"/> -->
          <!-- :mergeCellMethod="activeName === 'first'?objectSpanMethod1:objectSpanMethod2" -->
        <FilterTable
          v-show="activeName === 'first'"
          ref="table"
          :columns="columns"
          height="auto"
          v-loading="loading"
          :mergeCellMethod="objectSpanMethod1"
          :dataSource="teamdDataSource"
          :isPagination="false"
          :isSelectColumn="false"
          :isColumnFilter="false"
          selectionType="single"
          :onColumnsChange="columns => this.columns = columns"
        ></FilterTable>
        <FilterTable
          v-show="activeName === 'second'"
          ref="table"
          :columns="columns2"
          height="auto"
          v-loading="loading"
          :mergeCellMethod="objectSpanMethod2"
          :dataSource="prodDataSource"
          :isPagination="false"
          :isSelectColumn="false"
          :isColumnFilter="false"
          selectionType="single"
          :onColumnsChange="columns2 => this.columns2 = columns2"
        ></FilterTable>
      </div>
    </div>


  </div>
</template>

<script>
import {
  qrySubmitOrderOEMReports
 } from '@/api/report/retail/OrderAnalysis';
import {
  getMerge,
  getOrgByOrgType,
  getSaleInfoMaintain,
  getBrandList,
  getSeriesList,
  getModelList,
 } from '@/api/report/retail/clueFunnelAnalysis';
import { getlistAllData } from '@/api/common/org/dealerCompany';
import { dictionary } from '@/utils/dictMixin';
import Chart1 from '@/charts/preSale/chart1';
import { authority } from '@/utils/authMixin';
import { arrayObjDeWeight, integration, GetPercent, computedAll, getTextByJs } from '@/utils/index';
import { ObjectAssign, sortRule } from '@/components/DataMerge';
import moment from 'moment';
export default {
  name: 'OrderAnalysisOEM',
  mixins: [dictionary,authority],
  components: {
    Chart1
  },
  data() {
    return {
      columns: this.createTableColumns(),
      columns2: this.createTableColumns2(),
      dataSource: [],
      teamdDataSource: [],//团队表格数据
      prodDataSource: [],//产品表格数据
      loading:false,
      initDataSource: [],
      topFilterList: this.createTopFilters(),
      fetchParams: {},
      visible: false,
      activeName: 'first',
    };
  },
  methods: {
    createTopFilters() {
      return [
        {
          type: 'DATE',
          label: '日期',
          fieldName: 'completeDate',
          placeholder: '',
          dateType: 'exactdate',
          initialValue: moment().format("YYYY-MM-DD")
          // change: (val, fieldName) => {
          //   // console.log(val,fieldName)
          //   this.quarterTime = val;
          // }
        },
        {
          type: 'SELECT',
          label: '区域',
          fieldName: 'regionId',
          placeholder: '请选择...',
          itemList: [],
          change:val=>{
            // console.log(val)
            this.getSaleInfoMaintain(val)
          }
        },
        {
          type: 'INPUT_CASCADER',
          label: '省市',
          fieldName: 'provinceId',
          placeholder: '请选择...',
          options: { titles: ['省', '市'] },
          itemList: [],
          change:val=>{
            // console.log(val)
            this.getSaleInfoMaintain(null,val)
          }
        },
        {
          type: 'MULTIPLE_SELECT',
          label: '经销商',
          fieldName: 'dealerId',
          placeholder: '请选择...',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '品牌',
          fieldName: 'brandId',
          placeholder: '请选择',
          itemList: [],
          change: val => {
            this.changeBrandSelect(val);
          }
        },
        {
          type: 'SELECT',
          label: '车系',
          fieldName: 'seriesId',
          placeholder: '请选择',
          itemList: [],
          change: val => {
            this.changeSeriesSelect(val);
          }
        },
        {
          type: 'MULTIPLE_SELECT',
          label: '车型',
          fieldName: 'modelId',
          placeholder: '请选择',
          itemList: [],
          // change: val => {
          //   this.changeModelSelect(val);
          // }
        },
      ];
    },

    async qrySubmitOrderOEMReports() {
      this.loading = true;
      const res = await qrySubmitOrderOEMReports(this.fetchParams);
      if (res.resultCode === 200) {
        this.loading = false;
        let list = res.data.salesVinTeamTableList;//团队
        if (list.length > 0) {
          list = sortRule(list, 'regionId');
          list = sortRule(list, 'provinceId');
          let all = computedAll([...this.columns],list)
          all['regionId'] = 'all';
          all['provinceId'] = 'all';
          all['ownerCode'] = 'all';
          all['regionName'] = '全部';
          all['provinceName'] = '全部';
          all['ownerName'] = '全部';
          list.unshift(all);
          list.forEach(x=>{
              x['monthSame'] = GetPercent(x.monthSum - x.monthYoy,x.monthYoy)
              x['monthSequential'] = GetPercent(x.monthSum - x.monthMom,x.monthMom)
              x['quarterSame'] = GetPercent(x.quarterSum - x.quarterYoy,x.quarterYoy)
              x['quarterSequential'] = GetPercent(x.quarterSum - x.quarterQoq,x.quarterQoq)
              x['yearSame'] = GetPercent(x.yearSum - x.yearYoy,x.yearYoy)
          })
        }
        console.log(list)
        this.teamdDataSource = list;
        this.dataSource = list;
        // table数据处理
        let columns2 = this.createTableColumns2()
        let list2 = res.data.salesVinProductTableList;//产品
        if (list2.length > 0) {
          list2 = sortRule(list2, 'seriesId');
          let all = computedAll([...columns2],list2)
          all['seriesId'] = 'all';
          all['modelId'] = 'all';
          all['seriesName'] = '全部';
          all['modelName'] = '全部';
          list2.unshift(all);
          list2.forEach(x=>{
              x['monthSame'] = GetPercent(x.monthSum - x.monthYoy,x.monthYoy)
              x['monthSequential'] = GetPercent(x.monthSum - x.monthMom,x.monthMom)
              x['quarterSame'] = GetPercent(x.quarterSum - x.quarterYoy,x.quarterYoy)
              x['quarterSequential'] = GetPercent(x.quarterSum - x.quarterQoq,x.quarterQoq)
              x['yearSame'] = GetPercent(x.yearSum - x.yearYoy,x.yearYoy)
          })
        }
        this.prodDataSource = list2;
        console.log(this.prodDataSource)
      }
    },
    changeHandle(val) {
      // console.log(val)
      if (!val.completeDate) {
        val.completeDate = moment().format("YYYY-MM-DD");
      }
      if (val.modelId && val.modelId.length === 0 && val.brandId && val.seriesId) {
        let list = this.topFilterList.find(item=>item.fieldName==='modelId').itemList;
        val.modelIds = getTextByJs(list,'value')
      }else if (val.modelId && val.modelId.length > 0) {
        val.modelIds = getTextByJs(val.modelId)
      }else{
        val.modelIds = val.modelId
      }
      if (val.dealerId && val.dealerId.length === 0 && (val.regionId || val.provinceId)) {
        let list = this.topFilterList.find(item=>item.fieldName==='dealerId').itemList;
        val.ownerCode = getTextByJs(list,'value')
      }else if (val.dealerId && val.dealerId.length > 0) {
        val.ownerCode = getTextByJs(val.dealerId)
      }else{
        val.ownerCode = val.dealerId
      }
      if (!val.ownerCode) {
        val.ownerCode = undefined
      }
      //解决参数问题接口modelId
      // let fetchParams = {...val}
      // fetchParams.modelId = fetchParams.modelIds

      this.fetchParams = Object.assign({}, val);
      this.qrySubmitOrderOEMReports()
    },
    handleClick(tab, event) {
      console.log(this.activeName);
      // if (this.activeName === 'first') {
      //   this.dataSource = this.teamdDataSource
      //   this.columns = this.createTableColumns()
      // } else {
      //   this.dataSource = this.prodDataSource
      //   this.columns = this.createTableColumns2()
      // }
      // console.log(this.dataSource)
    },
    collapseHandle() {
      // this.$nextTick(() => {
      //   this.BaseTable.EXECUTE_RESET_HEIGHT();
      // });
    },
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    createTableColumns() {
      return [
        {
          title: '区域',
          dataIndex: 'regionName'
        },
        {
          title: '省市',
          dataIndex: 'provinceName'
        },
        {
          title: '经销商',
          dataIndex: 'ownerName'
        },
        {
          title: '结存订单',
          dataIndex: 'balanceSum'
        },
        {
          title: '本日新增',
          dataIndex: 'daySum'
        },
        {
          title: '周累计',
          dataIndex: 'weekSum'
        },
        {
          title: '月度',
          align: 'center',
          children: [
            {
              title: '月累计',
              dataIndex: 'monthSum',
            },
            {
              title: '去年同期累计',
              dataIndex: 'monthYoy',
            },
            {
              title: '月同比',
              dataIndex: 'monthSame',
              render: props => {
                return <span style={props.row.monthSame.indexOf("-") != -1 ? 'color:#FF4D4F':'color:#73D13D'}>{props.row.monthSame}</span>;
              }
            },
            {
              title: '上月同期累计',
              dataIndex: 'monthMom',
            },
            {
              title: '月环比',
              dataIndex: 'monthSequential',
              render: props => {
                return <span style={props.row.monthSequential.indexOf("-") != -1 ? 'color:#FF4D4F':'color:#73D13D'}>{props.row.monthSequential}</span>;
              }
            },
          ]
        },
        {
          title: '季度',
          align: 'center',
          children: [
            {
              title: '季累计',
              dataIndex: 'quarterSum',
            },
            {
              title: '去年同期累计',
              dataIndex: 'quarterYoy',
            },
            {
              title: '季同比',
              dataIndex: 'quarterSame',
              render: props => {
                return <span style={props.row.quarterSame.indexOf("-") != -1 ? 'color:#FF4D4F':'color:#73D13D'}>{props.row.quarterSame}</span>;
              }
            },
            {
              title: '上季同期累计',
              dataIndex: 'quarterQoq',
            },
            {
              title: '季环比',
              dataIndex: 'quarterSequential',
              render: props => {
                return <span style={props.row.quarterSequential.indexOf("-") != -1 ? 'color:#FF4D4F':'color:#73D13D'}>{props.row.quarterSequential}</span>;
              }
            },
          ]
        },
        {
          title: '年度',
          align: 'center',
          children: [
            {
              title: '年累计',
              dataIndex: 'yearSum',
            },
            {
              title: '去年同期累计',
              dataIndex: 'yearYoy',
            },
            {
              title: '年同比',
              dataIndex: 'yearSame',
              render: props => {
                return <span style={props.row.yearSame.indexOf("-") != -1 ? 'color:#FF4D4F':'color:#73D13D'}>{props.row.yearSame}</span>;
              }
            },
          ]
        },
      ];
    },
    createTableColumns2() {
      return [
        {
          title: '车系',
          dataIndex: 'seriesName'
        },
        {
          title: '车型',
          dataIndex: 'modelName'
        },
        {
          title: '结存订单',
          dataIndex: 'balanceSum'
        },
        {
          title: '本日新增',
          dataIndex: 'daySum'
        },
        {
          title: '周累计',
          dataIndex: 'weekSum'
        },
        {
          title: '月度',
          align: 'center',
          children: [
            {
              title: '月累计',
              dataIndex: 'monthSum',
            },
            {
              title: '去年同期累计',
              dataIndex: 'monthYoy',
            },
            {
              title: '月同比',
              dataIndex: 'monthSame',
              render: props => {
                return <span style={props.row.monthSame.indexOf("-") != -1 ? 'color:#FF4D4F':'color:#73D13D'}>{props.row.monthSame}</span>;
              }
            },
            {
              title: '上月同期累计',
              dataIndex: 'monthMom',
            },
            {
              title: '月环比',
              dataIndex: 'monthSequential',
              render: props => {
                return <span style={props.row.monthSequential.indexOf("-") != -1 ? 'color:#FF4D4F':'color:#73D13D'}>{props.row.monthSequential}</span>;
              }
            },
          ]
        },
        {
          title: '季度',
          align: 'center',
          children: [
            {
              title: '季累计',
              dataIndex: 'quarterSum',
            },
            {
              title: '去年同期累计',
              dataIndex: 'quarterYoy',
            },
            {
              title: '季同比',
              dataIndex: 'quarterSame',
              render: props => {
                return <span style={props.row.quarterSame.indexOf("-") != -1 ? 'color:#FF4D4F':'color:#73D13D'}>{props.row.quarterSame}</span>;
              }
            },
            {
              title: '上季同期累计',
              dataIndex: 'quarterQoq',
            },
            {
              title: '季环比',
              dataIndex: 'quarterSequential',
              render: props => {
                return <span style={props.row.quarterSequential.indexOf("-") != -1 ? 'color:#FF4D4F':'color:#73D13D'}>{props.row.quarterSequential}</span>;
              }
            },
          ]
        },
        {
          title: '年度',
          align: 'center',
          children: [
            {
              title: '年累计',
              dataIndex: 'yearSum',
            },
            {
              title: '去年同期累计',
              dataIndex: 'yearYoy',
            },
            {
              title: '年同比',
              dataIndex: 'yearSame',
              render: props => {
                return <span style={props.row.yearSame.indexOf("-") != -1 ? 'color:#FF4D4F':'color:#73D13D'}>{props.row.yearSame}</span>;
              }
            },
          ]
        },
      ];
    },

    // 合并行或列的计算方法
    // row:当前行 column:当前列 rowIndex:当前行号 columnIndex:当前列号
    objectSpanMethod1({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        if (rowIndex === 0) {
          row.regionName = '全部';
          row.provinceName = '全部';
          row.ownerName = '全部';
          return [1, 3];
        } else {
          // 与上一行不相等
          if (row.regionId !== (this.teamdDataSource[rowIndex - 1] || {}).regionId) {
            // 与上一行不相等,与下一行相等
            if (row.regionId === (this.teamdDataSource[rowIndex + 1] || {}).regionId) {
              return {
                rowspan: this.teamdDataSource.filter(x => row.regionId === x.regionId).length || 1,
                colspan: 1
              };
            } else {   // 与上一行不相等,与下一行不相等
              return [1, 1];
            }
          } else {     // 与上一行相等
            return [0, 0];
          }
        }
      } else if (columnIndex === 1) {
        if (rowIndex === 0) {
          return [0, 0];
        }
          // 与上一行不相等
          if (row.provinceId !== (this.teamdDataSource[rowIndex - 1] || {}).provinceId) {
            // 与上一行不相等,与下一行相等
            if (row.provinceId === (this.teamdDataSource[rowIndex + 1] || {}).provinceId) {
              return {
                rowspan: this.teamdDataSource.filter(x => row.provinceId === x.provinceId).length || 1,
                colspan: 1
              };
            } else {   // 与上一行不相等,与下一行不相等
              return [1, 1];
            }
          } else {     // 与上一行相等
            return [0, 0];
          }
      } else if (columnIndex === 2) {
        if (rowIndex === 0) {
          return [0, 0];
        }
      }
    },
    objectSpanMethod2({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        if (rowIndex === 0) {
          row.seriesName = '全部';
          return [1, 2];
        } else {
          // 与上一行不相等
          if (row.seriesId !== (this.prodDataSource[rowIndex - 1] || {}).seriesId) {
            // 与上一行不相等,与下一行相等
            if (row.seriesId === (this.prodDataSource[rowIndex + 1] || {}).seriesId) {
              return {
                rowspan: this.prodDataSource.filter(x => row.seriesId === x.seriesId).length || 1,
                colspan: 1
              };
            } else {   // 与上一行不相等,与下一行不相等
              return [1, 1];
            }
          } else {     // 与上一行相等
            return [0, 0];
          }
        }
      } else if (columnIndex === 1) {
        if (rowIndex === 0) {
          return [0, 0];
        }
      }
    },
    async getBrandList() {
      const res = await getBrandList();
      if (res.resultCode === 200) {
        this.topFilterList.find(item=>item.fieldName==='brandId').itemList = res.data.map(x => ({ value: x.brandId, text: x.brandName }));
        // this.topFilterList = [...this.topFilterList]
      }
    },
    async changeBrandSelect(brandsid) {
      if (!brandsid) {
        this.topFilterList.find(item=>item.fieldName==='seriesId').initialValue = '';
        this.topFilterList.find(item=>item.fieldName==='seriesId').itemList = [];
        this.topFilterList.find(item=>item.fieldName==='modelId').initialValue = '';
        this.topFilterList.find(item=>item.fieldName==='modelId').itemList = [];
      } else {
        const res = await getSeriesList(brandsid);
        if (res.resultCode === 200) {
          this.topFilterList.find(item=>item.fieldName==='seriesId').itemList = res.data.map(x => ({ value: x.seriesId, text: x.seriesName }));
        }
      }
    },
    async changeSeriesSelect(seriessid) {
      const brandsid = this.topFilterList.find(item=>item.fieldName==='brandId').initialValue;
      if (!brandsid || !seriessid) {
        this.topFilterList.find(item=>item.fieldName==='modelId').initialValue = '';
        this.topFilterList.find(item=>item.fieldName==='modelId').itemList = [];
      } else {
        const res = await getModelList(brandsid, seriessid);
        if (res.resultCode === 200) {
          this.topFilterList.find(item=>item.fieldName==='modelId').itemList = res.data.map(x => ({ value: x.modelId, text: x.modelName }));
        }
      }
    },
    // 获取省市
    async getCityList() {
      let self = this;
      //  console.log(this.provinceId,this.cityId,"this.formList3[89]")
      await getlistAllData().then(res=>{
        // console.log('城市', res)
        let province=[],listAllData=[];
        listAllData=res.data
        listAllData.forEach(x=>{
          // 筛选省
          if(x.parentRegionId == null){
            province.push({text:x.regionName,value:`${x.regionId}`})
          }
        })
        province.forEach(y=>{
          let initCity=[]
          listAllData.forEach(x=>{
            // 市
            if(x.parentRegionId == y.value){
              initCity.push({text:x.regionName,value:`${x.regionId}`})
            }
          })
          y.children = initCity
        })
        // this.listAllData = province;
        this.topFilterList.find(item=>item.fieldName==='provinceId').itemList = province;
        // console.log("省市",province)
      })
    },
    async getMerge() {
      const res = await getMerge();
      if (res.resultCode === 200) {
        // console.log(res)
        this.getOrgByOrgType({orgType:res.data.isDisArea === 10041001?15061006:15061007})//15061006:大区 15061007:小区
      }
    },
    async getOrgByOrgType(data) {
      const res = await getOrgByOrgType(data);
      if (res.resultCode === 200) {
        this.topFilterList.find(item=>item.fieldName==='regionId').itemList = res.data.map(x => ({ value: x.orgId, text: x.orgName }));
      }
    },
    async getSaleInfoMaintain(regionId,Cities) {
      let orgId = regionId === '' ? regionId:(regionId || this.topFilterList.find(item=>item.fieldName==='regionId').initialValue)
      let provinceId = Cities === '' ? Cities:(Cities || this.topFilterList.find(item=>item.fieldName==='provinceId').initialValue || '');
      // debugger
      let data = {
        pageSize: 999,
        orgId: orgId || undefined,
        provinceId: provinceId.split(",")[0] || undefined,
        cityId: provinceId.split(",")[1] || undefined
      }
      const res = await getSaleInfoMaintain(data);
      if (res.resultCode === 200) {
        this.topFilterList.find(item=>item.fieldName==='dealerId').itemList = res.data.map(x => ({ value: x.orgId, text: x.dealerName }));
        this.topFilterList.find(item=>item.fieldName==='dealerId').initialValue = ''
      }
    },
  },
  mounted() {
    // this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  created() {
    this.getMerge()
    this.getSaleInfoMaintain()
    this.getCityList()
    this.getBrandList()
    this.changeHandle({})
  }
};
</script>

<style lang="less" scoped>
#Chartdiv{

  .chartSearch{
    display:flex;
    align-items: center;
    justify-content: space-between;
    padding:12px 32px;
    background:#fff;
    border-bottom: 1px solid rgba(0,4,10,0.08);
  }
  .Chartmain{
    background:#fff;
    .Chartleft{
      border-left: 1px dashed rgba(0,4,10,0.08);
    }
  }
}
.Chartf{
  width:100%;
  // max-height: 400px;
  .ChartTop{
    font-size: 16px;
    font-weight: 600;
    line-height: 58px;
    padding-left:32px;
  }
}


.maintop{
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  overflow: hidden;
  background:#FFF;
  padding-left: 12px;
  padding-right: 12px;
  border-bottom: 1px solid rgba(0,4,10,0.08);
  .lazyLoadTab {
    /deep/ .el-tabs__header,.is-top{
      margin-bottom: 0;
    }
    /deep/ .el-tabs__active-bar{
      height: 4px;
    }
    /deep/ .el-tabs__nav-wrap::after{
      height: 0;
    }
  }
}

.tabShow{
  min-height: 300px;
}
</style>
